package com.websql.yousql.config.dataSource;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class DynamicDataSourceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        String dbName = split[split.length - 1];

        System.out.println("...【RequestURI】...requestURI:  " + requestURI);
        System.out.println("...【DynamicDataSourceInterceptor】...动态数据源接收到参数   dbName:  " + dbName);

        RoutingDataSourceContext.setDataSourceRoutingKey(dbName);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理动态数据源key
        RoutingDataSourceContext.clear();
    }
}
